package com.sq.universe.flowable.listener;

import com.sq.universe.flowable.service.WorkflowService;
import org.flowable.common.engine.impl.el.FixedValue;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.task.service.delegate.TaskListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Component(value = "commonTaskListener")
public class CommonTaskListener  implements TaskListener, Serializable {

    @Autowired
    private SpringClientFactory factory;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    @Lazy
    WorkflowService workflowService;

    private FixedValue module;
    private FixedValue url;
//    private FixedValue postHandler;



    private static RestTemplate restTemplateStatic;

    /**
     * 监听器中无法获取spring bean配置
     */
//    @PostConstruct
////    public void init() {
////        restTemplateStatic = this.restTemplate;
////    }
    @Override
    public void notify(DelegateTask delegateTask) {
//        ILoadBalancer lb =  factory.getLoadBalancer(module.getExpressionText()); //指定服务名
//        List<Server> allServers = lb.getAllServers();
//        List<Server> upServers = lb.getReachableServers();
//        restTemplateStatic.patchForObject()
//        restTemplateStatic.postForObject("http://" + module.getExpressionText() + url.getExpressionText(),String.class);
        Map taskInfo = workflowService.queryTaskInfo(delegateTask.getProcessInstanceId());
        Map map = new HashMap<>();
        map.put("processInstanceId",delegateTask.getProcessInstanceId());
        map.putAll(taskInfo);
        restTemplate.postForObject("http://" + module.getExpressionText() + url.getExpressionText(),map,Map.class);
    }


//    @Override
//    public void notify(DelegateExecution delegateExecution) {
//        restTemplateStatic.getForObject("http://" + module.getExpressionText() + url.getExpressionText(),String.class);
//    }
}
